{% extends 'surveillanceapp/base.html' %}
{% load static %}

{% block extracss %}
    <style>
        .vehicle-img{
            width: 152px;
            height: 152px;
            display: block;
        }
        .vehicle-block{
            border-width: 5px;
            border-style: solid;
            border-color: #394a59;
            margin-left: 1%;
            margin-right: 1%;
            text-align: center;
            display: inline-block;
        }
        .vehicle-block p{
            font-size: 150%;
            color: #394a59;
        }
        .outgoing-count{
            font-weight: bold;
            font-size: 200%;
            margin-top: -2%;
            color: #394A59;
        }
        button{
            padding-top: 2% !important;
            padding-bottom: 2% !important;
        }
        .btn-text{
            font-size: 150%;
            font-weight: bold;
        }
    </style>
{% endblock %}

{% block extraheadjs %}
    <script src="{% static 'js/highcharts.js' %}"></script>
{% endblock %}

{% block main-content %}
    <div class="row">
        <div class="col-lg-2">
            <button id="video-play-btn" class="btn btn-block btn-primary"><span class="fa fa-play-circle fa-2x" style="margin-right: 6%;"></span> <span class="btn-text"> Play Video</span></button>
        </div>
        <div class="col-lg-8">
            <div class="progress" style="margin-top:1%; background: #394a59;">
                <div id="video-progress-bar" class="progress-bar video-progress" role="progressbar" style="width: {{ video.analysed_percentage }}%; background: #d8ab5a;">
                    {{ video.analysed_percentage }}%
                </div>
            </div>
        </div>
        <div class="col-lg-2">
            {% if not video.report %}
                <button data-href="" id="report-btn" class="btn btn-block btn-success pull-right" style="display: none">
                    <span class="fas fa-chart-bar fa-2x" style="margin-right: 6%"></span> <span class="btn-text"> View Report</span>
                </button>
            {% else %}
                <button data-href="{% url 'surveillanceapp:report' video.station.station_id video.video_id %}" id="report-btn" class="btn btn-block btn-success pull-right">
                    <span class="fas fa-chart-bar fa-2x" style="margin-right: 6%"></span> <span class="btn-text"> View Report</span>
                </button>
            {% endif %}
        </div>
    </div>
    <div id="vehicle-wrapper" class="row" style="margin-top: 1%; display: none;">
        <div class="col-lg-12" style="text-align: center;">
            <div class="vehicle-block">
                <img src="{% static 'img/tempo.png' %}" class="vehicle-img">
                <p>Tempo</p>
                <h2 class="outgoing-count" data-vclass="Tempo">0</h2>
            </div>
            <div class="vehicle-block">
                <img src="{% static 'img/bike.png' %}" class="vehicle-img">
                <p>Bike</p>
                <h2 class="outgoing-count" data-vclass="Bike">0</h2>
            </div>
            <div class="vehicle-block">
                <img src="{% static 'img/car.png' %}" class="vehicle-img">
                <p>Car</p>
                <h2 class="outgoing-count" data-vclass="Car">0</h2>
            </div>
            <div class="vehicle-block">
                <img src="{% static 'img/taxi.png' %}" class="vehicle-img">
                <p>Taxi</p>
                <h2 class="outgoing-count" data-vclass="Taxi">0</h2>
            </div>
            <div class="vehicle-block">
                <img src="{% static 'img/micro.png' %}" class="vehicle-img">
                <p>Micro</p>
                <h2 class="outgoing-count" data-vclass="Micro">0</h2>
            </div>
            <div class="vehicle-block">
                <img src="{% static 'img/pickup.png' %}" class="vehicle-img">
                <p>Pickup</p>
                <h2 class="outgoing-count" data-vclass="Pickup">0</h2>
            </div>
            <div class="vehicle-block">
                <img src="{% static 'img/bus.png' %}" class="vehicle-img">
                <p>Bus</p>
                <h2 class="outgoing-count" data-vclass="Bus">0</h2>
            </div>
            <div class="vehicle-block">
                <img src="{% static 'img/truck.png' %}" class="vehicle-img">
                <p>Truck</p>
                <h2 class="outgoing-count" data-vclass="Truck">0</h2>
            </div>
        </div>
    </div>
    <div class="row" style="padding-top: 2%">
        <div id="graph-body" class="col-lg-12">
            <div class="col-lg-6" id="number-graph">

            </div>
            <div class="col-lg-6" id="congestion-graph">

            </div>
        </div>
    </div>
    <div class="row" style="padding-top: 1%">
        <div id="bargraph" class="col-lg-10 col-lg-push-1">
        </div>
    </div>
    <div class="row" id="summary-wrapper">
        <div class="col-lg-12">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <i class="fa fa-info-circle"></i> Analysis Notice
                </div>
                <div class="panel-body">
                    {% if not video.report %}
                        <div style="font-size: 250%;">
                            The video has not been analysed yet.
                        </div>
                        <div style="font-size: 150%; margin-top: 2%">
                            Therefore, no statistical information is available for the video.
                            Play the video to observe its real time analysis which includes:
                            <ull>
                                <li>Number of vehicles in the road at current time</li>
                                <li>Number of vehicles that have passed through the road</li>
                                <li>Congestion index of the road at current time</li>
                            </ull>
                        </div>
                        <div style="font-size: 250%; margin-top: 2%">
                            A detailed report with graphs will also be available after analysis
                        </div>
                    {% else %}
                        <p style="font-size: 250%;">
                            The video has been analysed upto <strong>{{ video.analysed_percentage }} %</strong> of its total duration.
                        </p>
                        <div style="font-size: 200%; margin-top:2%;">
                            During this analysis period:
                            <ull>
                                <li>Total number of vehicles that have passed through: <strong>{{ video.surveillance_report.outgoing_vehicle_count }}</strong></li>
                                <li>Average congestion index of the road: <strong>{{ video.surveillance_report.avg_congestion_index| floatformat:2 }}</strong></li>
                            </ull>
                        </div>
                        <div style="font-size: 200%; margin-top:2%;">
                            For a detailed report, view the analysis report that is available now. You can also re-analyse the video by clicking the play button
                        </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
{% endblock %}

{% block extrajs %}
    <script>
        var playbtn = document.querySelector('#video-play-btn');
        var reportbtn = document.querySelector('#report-btn');
        var progressbar = document.querySelector('#video-progress-bar');
        var outgoing_infos = document.querySelectorAll('.outgoing-count');
        var outgoing_box = document.querySelector('#vehicle-wrapper');
        var summary_box = document.querySelector('#summary-wrapper');
        var socket = null;
        var numbergraph;
        var congestiongraph;
        var bargraph;
        var bargraphoptions;

        function cleargraph() {
            numbergraph = Highcharts.chart('number-graph', {
                credits:{
                    enabled: false
                },
                title: {
                    text: 'Total Number of Vehicles per second interval'
                },
                plotOptions: {
                    series: {
                        pointStart: 1
                    }
                },
                yAxis: {
                    title: {
                        text: 'Number of Vehicles'
                    }
                },
                xAxis: {
                    title: {
                        text: 'Time(seconds)'
                    }
                },
                series: [{
                    name: 'No.of vehicles',
                    color: '#296789',
                    data: []
                }]
            });

            congestiongraph = Highcharts.chart('congestion-graph', {
                credits:{
                    enabled: false
                },
                title: {
                    text: 'Approx Vehicle Congestion per second interval'
                },
                plotOptions: {
                    series: {
                        pointStart: 1
                    }
                },
                yAxis: {
                    title: {
                        text: 'Congestion Index'
                    }
                },
                xAxis: {
                    title: {
                        text: 'Time(seconds)'
                    }
                },
                series: [{
                    name: 'Congestion index',
                    color: '#7c212c',
                    data: []
                }]
            });

            bargraphoptions = {
                credits:{
                    enabled: false
                },
                chart: {
                    type: 'bar'
                },
                title: {
                    text: 'No. of vehicles in the road (by vehicle class) currently in the road '
                },
                xAxis: {
                    categories: ['Tempo', 'Bike', 'Car', 'Taxi', 'Micro', 'Pickup', 'Bus', 'Truck'],
                    title: {
                        text: null
                    }
                },
                yAxis: {
                    min: 0,
                    max: 20,
                    title: {
                        text: 'No.of vehicles',
                        align: 'high'
                    },
                    labels: {
                        overflow: 'justify'
                    }
                },
                plotOptions: {
                    bar: {
                        dataLabels: {
                            enabled: true
                        }
                    }
                },
                series: [{
                    name: 'No.of vehicles',
                    color: '#1d6c0e',
                    data: []
                }]
            };

            bargraph = Highcharts.chart('bargraph', bargraphoptions);
        }

        playbtn.addEventListener('click',function (event) {
            video_url = '{{ video.video_id }}';
            socket = new WebSocket('ws://'+window.location.host+'/video/'+video_url);

            socket.onopen = function open() {
                console.log('Main Websocket connection has opened successfully');
                socket.send(JSON.stringify({
                    'start': true,
                    'message': 'You can start the video'
                }));
                reportbtn.style.display = 'none';
            };
            socket.onclose = function close(ev) {
                console.log('Main Websocket connection is now being closed');
                reportbtn.style.display = 'inline';
                reportbtn.setAttribute('data-href',"{% url 'surveillanceapp:report' video.station.station_id video.video_id %}")
            };
            socket.onmessage = function message(event) {
                var received = JSON.parse(event.data);
                if(received['type'] == 'eof'){
                    socket.close(1000,'Server closed it');
                    {#showbtn();#}
                }
                else if(received['type'] == 'progress') {
                    progressbar.style.width = received['percentage'].toString()+'%';
                    progressbar.textContent = received['percentage'].toString()+'%';
                    if(received['outgoing_changed'] == true){   // To only update the elements if there is a change in the count
                        outgoing_count = received['outgoing_count'];
                        console.log(outgoing_count);
                        outgoing_infos.forEach(function (vclass_info) {
                            vclass_info.textContent = outgoing_count[vclass_info.getAttribute('data-vclass')];
                        });
                    }
                }
                else if(received['type'] == 'normal') {
                    var numbercount = received['numbercount'];
                    var congcount = received['congcount'];
                    var vclasscount = received['vclasscount'];
                    var shift = numbergraph.series[0].data.length > 20;
                    numbergraph.series[0].addPoint(numbercount, true, shift);
                    congestiongraph.series[0].addPoint(congcount, true, shift);
                    bargraphoptions.series[0].data = vclasscount;
                    bargraph.update(bargraphoptions,true);
                }
            };
            if(socket.readyState == WebSocket.OPEN){
                socket.onopen();
            }
            summary_box.style.display = 'none';
            outgoing_box.style.display = 'block';
            cleargraph();
            reportbtn.style.display = 'none';
        });

        reportbtn.addEventListener('click',function (ev) {
            window.location.href = this.getAttribute('data-href');
        });

    </script>
{% endblock %}